<template>
  <div class="trace-search-container">
    <div class="page-header">
      <h1>溯源查询</h1>
      <p>输入批次ID或扫描二维码查询茶叶完整溯源信息</p>
    </div>

    <el-card class="search-card">
      <div class="search-form">
        <el-input
          v-model="searchQuery"
          placeholder="请输入批次ID进行溯源查询"
          size="large"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" :loading="searching" type="primary">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
          </template>
        </el-input>
      </div>

      <div class="quick-actions">
        <el-button @click="openScanner" :disabled="!canUseCamera">
          <el-icon><Camera /></el-icon>
          扫描二维码
        </el-button>
        <el-button @click="showExamples">
          <el-icon><InfoFilled /></el-icon>
          查看示例
        </el-button>
      </div>
    </el-card>

    <!-- 搜索结果 -->
    <el-card v-if="searchResults.length > 0" class="results-card">
      <template #header>
        <h3>搜索结果</h3>
      </template>
      
      <div class="batch-list">
        <el-card 
          v-for="batch in searchResults" 
          :key="batch._id"
          class="batch-item"
          shadow="hover"
          @click="goToTraceDetail(batch.batchId)"
        >
          <div class="batch-info">
            <div class="batch-header">
              <h4>{{ batch.name }}</h4>
              <el-tag :type="getStatusType(batch.status)">
                {{ getStatusText(batch.status) }}
              </el-tag>
            </div>
            <p class="batch-id">批次ID: {{ batch.batchId }}</p>
            <p class="batch-variety">品种: {{ batch.variety }}</p>
            <p class="batch-origin" v-if="batch.production?.origin">
              产地: {{ batch.production.origin.province }} {{ batch.production.origin.city }}
            </p>
          </div>
          <el-icon class="batch-arrow"><ArrowRight /></el-icon>
        </el-card>
      </div>
    </el-card>

    <!-- 示例对话框 -->
    <el-dialog v-model="showExampleDialog" title="示例批次ID" width="500px">
      <div class="example-list">
        <div class="example-item" v-for="example in examples" :key="example.id">
          <el-tag @click="useExample(example.id)" style="cursor: pointer;">
            {{ example.id }}
          </el-tag>
          <span class="example-name">{{ example.name }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="showExampleDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 空状态 -->
    <el-empty v-if="hasSearched && searchResults.length === 0" description="未找到匹配的批次信息">
      <el-button type="primary" @click="clearSearch">重新搜索</el-button>
    </el-empty>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import { Search, Camera, InfoFilled, ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()

// 状态
const searchQuery = ref('')
const searchResults = ref([])
const searching = ref(false)
const hasSearched = ref(false)
const showExampleDialog = ref(false)

// 示例数据
const examples = ref([
  { id: 'TEA2024001', name: '西湖龙井精品茶' },
  { id: 'TEA2024002', name: '安溪铁观音' },
  { id: 'TEA2024003', name: '云南普洱' }
])

// 计算属性
const canUseCamera = computed(() => {
  return navigator.mediaDevices && navigator.mediaDevices.getUserMedia
})

// 方法
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入批次ID')
    return
  }

  searching.value = true
  hasSearched.value = true

  try {
    // 首先尝试精确匹配
    const response = await apiMethods.batches.getByBatchId(searchQuery.value.trim())
    if (response.data.success && response.data.data?.batch) {
      console.log('搜索返回的批次数据:', response.data.data.batch)
      searchResults.value = [response.data.data.batch]
    } else {
      // 如果精确匹配失败，尝试模糊搜索
      const searchResponse = await apiMethods.batches.search({
        keyword: searchQuery.value.trim(),
        page: 1,
        limit: 10
      })
      searchResults.value = searchResponse.data.data?.list || []
    }

    if (searchResults.value.length === 0) {
      ElMessage.info('未找到匹配的批次信息')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
    searchResults.value = []
  } finally {
    searching.value = false
  }
}

const openScanner = () => {
  ElMessage.info('二维码扫描功能开发中')
  // TODO: 实现二维码扫描功能
}

const showExamples = () => {
  showExampleDialog.value = true
}

const useExample = (exampleId) => {
  searchQuery.value = exampleId
  showExampleDialog.value = false
  handleSearch()
}

const goToTraceDetail = (batchId) => {
  console.log('跳转到溯源详情，batchId:', batchId)
  router.push(`/trace/${batchId}`)
}

const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
  hasSearched.value = false
}

const getStatusType = (status) => {
  const statusMap = {
    'created': 'info',
    'production': 'warning',
    'logistics': 'primary', 
    'sales': 'success',
    'consumed': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'created': '已创建',
    'production': '生产中',
    'logistics': '物流中',
    'sales': '销售中',
    'consumed': '已消费'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
.trace-search-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.search-input {
  max-width: 600px;
  margin: 0 auto;
  display: block;
}

.quick-actions {
  text-align: center;
  gap: 12px;
  display: flex;
  justify-content: center;
}

.results-card {
  margin-bottom: 20px;
}

.batch-list {
  display: grid;
  gap: 16px;
}

.batch-item {
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.batch-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.batch-info {
  flex: 1;
}

.batch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.batch-header h4 {
  margin: 0;
  color: #2c3e50;
}

.batch-id, .batch-variety, .batch-origin {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.batch-arrow {
  color: #c0c4cc;
  font-size: 18px;
}

.example-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.example-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.example-name {
  color: #606266;
  font-size: 14px;
}

@media (max-width: 768px) {
  .trace-search-container {
    padding: 10px;
  }

  .quick-actions {
    flex-direction: column;
  }

  .batch-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>